package org.loofer.uikit;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.widget.Button;

public class TimerButton extends Button {
    private static final long UNIT = 1000;
    private Drawable mDisableBackground;
    private long mDuration;
    private Drawable mEnableBackground;
    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private String mNormalText;
    private final Runnable mTimerRunnable = new Runnable() {
        public void run() {
            if (TimerButton.this.mDuration <= 0) {
                TimerButton.this.setText(TimerButton.this.mNormalText);
                TimerButton.this.setEnableStatus(true);
                return;
            }
            TimerButton.this.setText(String.format(TimerButton.this.mTimerTextFormat, new Object[]{Long.valueOf(TimerButton.this.mDuration / TimerButton.UNIT)}));
            TimerButton.this.mDuration = TimerButton.this.mDuration - TimerButton.UNIT;
            TimerButton.this.mHandler.postDelayed(TimerButton.this.mTimerRunnable, TimerButton.UNIT);
        }
    };
    private String mTimerTextFormat;

    public TimerButton(Context context) {
        super(context);
    }

    public TimerButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TimerButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(21)
    public TimerButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public void startTimer(String timerTextFormat, String normalText, long duration) {
        startTimer(timerTextFormat, normalText, duration, false);
    }

    public void startTimer(String timerTextFormat, String normalText, long duration, boolean enable) {
        this.mDuration = duration;
        this.mTimerTextFormat = timerTextFormat;
        this.mNormalText = normalText;
        setEnableStatus(enable);
        this.mHandler.post(this.mTimerRunnable);
    }

    public void setDisableBackground(Drawable disableBackground) {
        this.mEnableBackground = getBackground();
        this.mDisableBackground = disableBackground;
    }

    public void setEnableStatus(boolean enable) {
        setEnabled(enable);
        if (enable) {
            setBackgroundDrawable(this.mEnableBackground);
        } else {
            setBackgroundDrawable(this.mDisableBackground);
        }
    }
}
